<template>
    <div class="page">
        <h1>JSON文档翻译</h1>
        <div class="flex-default">
            <div class="container zh-container">
                <el-input
                    class="textarea-style"
                    autosize
                    type="textarea"
                    placeholder="请输入内容"
                    resize="none"
                    v-model="jsonText">
                </el-input>
            </div>
            <div class="btn-container">
                <el-form ref="form" :model="form" label-width="80px">
                    <el-form-item label="APPID">
                        <el-input v-model="form.appid"></el-input>
                    </el-form-item>
                    <el-form-item label="密钥">
                        <el-input v-model="form.key"></el-input>
                    </el-form-item>
                    <el-form-item label="源语言">
                        <el-select v-model="form.from" style="width: 100%;" placeholder="请选择源语言">
                            <el-option
                                v-for="item in langOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="目标语言">
                        <el-select v-model="form.to" style="width: 100%;" placeholder="请选择目标语言">
                            <el-option
                                v-for="item in langOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <!-- <el-form-item label="领域类型">
                        <el-select v-model="form.domain" style="width: 100%;" placeholder="请选择领域类型">
                            <el-option
                                v-for="item in domainOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item> -->
                </el-form>
                <el-button style="width: 100%;margin: 5px 0;" type="primary" @click="submit">翻译</el-button>
                <el-button style="width: 100%;margin: 5px 0;" type="primary" @click="clearContent">清空</el-button>
                <p class="tips-style">
                    <i class="el-icon-info"></i><span>提示：<br /></span>
                    <span>APPID为百度翻译API的APPID，可以在百度翻译开放平台申请，申请地址：<a href="https://api.fanyi.baidu.com/" target="_blank">https://api.fanyi.baidu.com/</a><br /></span>
                    <span>左边的翻译源数据必须是对象格式的字符串，右边翻译完成需要一定的等待时间，每次翻译间隔2s，翻译之后的结果遵循首字母大写，其余小写。翻译完成之后，右上角会显示复制按钮进行复制！</span>
                </p>
            </div>
            <div class="container en-container">
                <el-input
                    class="textarea-style"
                    autosize
                    type="textarea"
                    resize="none"
                    placeholder="请输入内容"
                    v-model="returnText">
                </el-input>
                <i v-if="isShowCopy" class="icon-copy el-icon-document-copy" @click="copyRes"></i>
            </div>
        </div>
    </div>
</template>

<script>
import $ from 'jquery'
import {MD5} from '@/assets/js/md5.js'
export default {
    name: 'HelloWorld',
    data () {
        return {
            langOptions: [
                {
                    value: 'en',
                    label: '英文'
                },
                {
                    value: 'zh',
                    label: '中文'
                }
            ],
            domainOptions: [
                {
                    value: 'it',
                    label: '信息技术领域(中文-> 英语、英语 -> 中文)'
                },
                {
                    value: 'academic',
                    label: '学术论文领域(中文-> 英语、英语 -> 中文)'
                },
                {
                    value: 'novel',
                    label: '网络文学领域(中文-> 英语)'
                }
            ],
            isShowCopy: false,
            jsonText: '',
            returnText: '',
            form: {
                appid: '20240613002123456',
                from: 'zh',
                to: 'en',
                domain: 'it',
                key: 'UARsI6mTCuj_123456789'
            },
            currentObj: {}
        }
    },
    watch: {
        jsonText: {
            handler(val) {
                if (!val) {
                    this.isShowCopy = false
                    this.returnText = ''
                }
            },
            immediate: true
        }
    },
    methods: {
        // 提交
        async submit() {
            let that = this;
            if (this.jsonText && this.isJsonString(this.jsonText)) {
                let obj = this.currentObj;
                let ary = Object.keys(obj);
                for (let i=0; i<ary.length; i++) {
                    await new Promise((resolve, reject) => {
                        return setTimeout(() => {
                            that.requestTranslate(ary[i], obj[ary[i]])
                            if (i>=ary.length - 1) {
                                this.isShowCopy = true
                            }
                            resolve(ary[i])
                        }, 2000)
                    })
                }
            } else {
                this.$message.error('请输入正确的内容')
            }
        },
        // 清空
        clearContent() {
            this.jsonText = ''
            this.returnText = ''
            this.isShowCopy = false
        },
        // 去掉对象的无效值
        removeInvalidValues(obj) {
            return Object.keys(obj)
                .filter(key => obj[key] !== null && obj[key] !== undefined)
                .reduce((acc, key) => {
                acc[key] = obj[key];
                return acc;
                }, {});
        },
        // 判断是否为对象字符串
        isJsonString(str) {
            const obj = {};
            str.replace(/\s+/g, '').slice(1, -1).split(',').forEach(pair => {
                const [key, value] = pair.split(':').map(str => str.trim().replace(/"|'/g, ''));
                obj[key] = value;
            });
            let newObj = this.removeInvalidValues(obj);
            try {
                JSON.parse(JSON.stringify(newObj));
                this.currentObj = newObj
                return true;
            } catch (e) {
                return false;
            }
        },
        // 点击复制
        copyRes() {
            this.copyToClipboard(this.returnText)
            this.$message.success('复制成功')
        },
        // 复制内容
        copyToClipboard(text) {
            var textarea = document.createElement('textarea');
            textarea.style.position = 'fixed';
            textarea.style.opacity = 0;
            textarea.value = text;
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand('copy');
            document.body.removeChild(textarea);
        },
        // 处理字符串首字母大写
        capitalizeAfterQuestion(str) {
            return str.replace(/(\?|\.|\!)?(\w)/g, function(match, punct, letter, index, original) {
                // 如果是句号、问号后面的第一个字母，则转换为大写，其余字母转换为小写
                if (index === 0 || punct === '?' || punct === '.') {
                return letter.toUpperCase();
                }
                return letter.toLowerCase();
            });
        },
        // 请求翻译
        requestTranslate(objKey, qContent) {
            let that = this;
            let key = this.form.key
            let salt = new Date().getTime()
            // 获取sign
            let sign = MD5(this.form.appid + qContent + salt + key)
            // 发起请求
            return $.ajax({
                url: 'http://api.fanyi.baidu.com/api/trans/vip/translate',
                type: 'get',
                dataType: 'jsonp',
                data: {
                    q: qContent,
                    appid: this.form.appid,
                    salt: salt,
                    from: this.form.from,
                    to: this.form.to,
                    sign: sign
                },
                success: function (data) {
                    if (data.error_code) {
                        this.returnText = JSON.stringify(this.currentObj, null, 4)
                        return
                    }
                    this.currentObj[objKey] = that.capitalizeAfterQuestion(data.trans_result[0].dst)
                    this.returnText = JSON.stringify(this.currentObj, null, 4)
                }.bind(this),
                error: function (err) {
                    console.log(err);
                } 
            })
        }
    }
}
</script>

<style scoped>
h1 {
    font-size: 36px;
    font-weight: bolder;
    margin: 20px;
}
.page {
    padding: 0 20px;
}
.container {
    border: 1px solid #ccc;
    padding: 10px;
    width: 40%;
    height: calc(100vh - 100px);
    overflow-y: auto;
    border-radius: 10px;
}
.btn-container {
    width: 20%;
    margin: 0 20px;
}

.flex-default {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
}
.textarea-style {
    height: 100%;
    height: 100%;
    display: inline-block;
}
.textarea-style /deep/ .el-textarea__inner {
    height: 100% !important;
    font-size: 15px;
    line-height: 25px;
    border: none;
}
.en-container {
    position: relative;
}
.en-container .icon-copy {
    position: absolute;
    right: 15px;
    top: 15px;
    cursor: pointer;
    width: 30px;
    height: 30px;
    display: inline-block;
    font-size: 20px;
}
.tips-style {
    color: #666;
    line-height: 30px;
    margin-top: 10px;
}
</style>
